# -*- coding: utf-8 -*-
import actions
import committee
import models
import settings
from django import http
from django.contrib.auth import authenticate, login
from django.contrib.auth.models import User, Group
from django.core.context_processors import csrf
from django.shortcuts import render_to_response
from django.views.decorators.cache import never_cache

def guest_login(request):
    user = authenticate(username=settings.GUEST_USERNAME, password=settings.GUEST_PASSWORD)
    if user is None:
        user = User.objects.create_user(settings.GUEST_USERNAME, '', settings.GUEST_PASSWORD)
        user.first_name = u"Гость"
        user.save()
    if not user.is_active:
        user.is_active = True
        user.save()
    if not user.is_staff:
        user.is_staff = True
        user.save()
    try:
        group = Group.objects.get(name=settings.GUEST_GROUP)
    except Group.DoesNotExist:
        group = Group(name=settings.GUEST_GROUP)
        group.save()
    if group is not None and user.groups.filter(pk=group.pk).count() == 0:
        user.groups.add(group)
        user.save()
    user = authenticate(username=settings.GUEST_USERNAME, password=settings.GUEST_PASSWORD)    
    login(request, user)
    return http.HttpResponseRedirect("/")

def action_list(request):
    acts = actions.get_actions(request.user)
    if not acts:
        raise http.Http404()
    for act in acts:
        act["href"] = "../%s/%s/%s/" % (act["model"]._meta.app_label, act["model"]._meta.module_name, act["url"])
    return render_to_response("admin/action_list.html", {
        "actions": acts,
        "actions_href": ".",
        "title": u"Дополнительные действия",
        "user": request.user,
    })

def calc_scholarship(request):
    if not request.user.is_superuser and not request.user.has_perm(actions.DistributeScholarshipAction.permission):
        raise http.Http404()
    request.session[actions.SESSION_SCHOLARSHIP] = actions.get_scholarship_all_students(request)
    return http.HttpResponseRedirect("../")

def calc_welfare(request):
    if not request.user.is_superuser and not request.user.has_perm(actions.DistributeWelfareAction.permission):
        raise http.Http404()
    request.session[actions.SESSION_WELFARE] = actions.get_welfare_all_students(request)
    return http.HttpResponseRedirect("../")

def distribute_scholarship(request, student=None):
    if not request.user.is_superuser and not request.user.has_perm(actions.DistributeScholarshipAction.permission):
        raise http.Http404()
    if student is not None:
        try:
            student = models.Student.objects.get(pk=student)
        except models.Student.DoesNotExist:
            raise http.Http404()
        if not actions.check_faculty(request, student):
            raise http.Http404()
        scholarship = request.session.get(actions.SESSION_SCHOLARSHIP, {})
        try:
            scholarship[student] = committee.calc_scholarship(student)
        except committee.CommitteeException as ex:
            actions.add_error(scholarship, student, ex.message)
        request.session[actions.SESSION_SCHOLARSHIP] = scholarship
        return http.HttpResponseRedirect("../")
    extra_context = csrf(request)
    return actions.DistributeScholarshipAction().process(request, extra_context=extra_context)

def distribute_welfare(request, student=None):
    if not request.user.is_superuser and not request.user.has_perm(actions.DistributeWelfareAction.permission):
        raise http.Http404()
    if student is not None:
        try:
            student = models.Student.objects.get(pk=student)
        except models.Student.DoesNotExist:
            raise http.Http404()
        if not actions.check_faculty(request, student):
            raise http.Http404()
        welfare = request.session.get(actions.SESSION_WELFARE, {})
        try:
            welfare[student] = committee.calc_welfare(student)
        except committee.CommitteeException as ex:
            actions.add_error(welfare, student, ex.message)
        request.session[actions.SESSION_WELFARE] = welfare
        return http.HttpResponseRedirect("../")
    extra_context = csrf(request)
    return actions.DistributeWelfareAction().process(request, extra_context=extra_context)

def delete_scholarship_student(request, student):
    if not request.user.is_superuser and not request.user.has_perm(actions.DistributeScholarshipAction.permission):
        raise http.Http404()
    try:
        student = models.Student.objects.get(pk=student)
    except models.Student.DoesNotExist:
        raise http.Http404()
    scholarship = request.session.get(actions.SESSION_SCHOLARSHIP, {})
    if student not in scholarship:
        raise http.Http404()
    del scholarship[student]
    request.session[actions.SESSION_SCHOLARSHIP] = scholarship
    return http.HttpResponseRedirect("../../")

def delete_welfare_student(request, student):
    if not request.user.is_superuser and not request.user.has_perm(actions.DistributeWelfareAction.permission):
        raise http.Http404()
    try:
        student = models.Student.objects.get(pk=student)
    except models.Student.DoesNotExist:
        raise http.Http404()
    welfare = request.session.get(actions.SESSION_WELFARE, {})
    if student not in welfare:
        raise http.Http404()
    del welfare[student]
    request.session[actions.SESSION_WELFARE] = welfare
    return http.HttpResponseRedirect("../../")

@never_cache
def edit_scholarship_student(request, student):
    if not request.user.is_superuser and not request.user.has_perm(actions.DistributeScholarshipAction.permission):
        raise http.Http404()
    try:
        student = models.Student.objects.get(pk=student)
    except models.Student.DoesNotExist:
        raise http.Http404()
    extra_context = csrf(request)
    return actions.DistributeScholarshipAction().edit(request, extra_context, student)

def edit_welfare_student(request, student):
    if not request.user.is_superuser and not request.user.has_perm(actions.DistributeWelfareAction.permission):
        raise http.Http404()
    try:
        student = models.Student.objects.get(pk=student)
    except models.Student.DoesNotExist:
        raise http.Http404()
    extra_context = csrf(request)
    return actions.DistributeWelfareAction().edit(request, extra_context, student)    

@never_cache
def addelete_scholarship_student(request, student, clazz):
    if not request.user.is_superuser and not request.user.has_perm(actions.DistributeScholarshipAction.permission):
        raise http.Http404()
    try:
        student = models.Student.objects.get(pk=student)
    except models.Student.DoesNotExist:
        raise http.Http404()
    try:
        clazz = models.StudentClass.objects.get(pk=clazz)
    except models.StudentClass.DoesNotExist:
        raise http.Http404()
    if student.stud_classes.filter(pk=clazz.pk).count() == 0:
        raise http.Http404()
    scholarship = request.session.get(actions.SESSION_SCHOLARSHIP, {})
    if student not in scholarship:
        raise http.Http404()
    classes = scholarship[student]
    if clazz in classes:
        del classes[clazz]
    else:
        classes[clazz] = committee.calc_scholarship_payment(clazz)
    scholarship[student] = classes
    request.session[actions.SESSION_SCHOLARSHIP] = scholarship
    return http.HttpResponseRedirect("../")

@never_cache
def addelete_welfare_student(request, student, clazz):
    if not request.user.is_superuser and not request.user.has_perm(actions.DistributeWelfareAction.permission):
        raise http.Http404()
    try:
        student = models.Student.objects.get(pk=student)
    except models.Student.DoesNotExist:
        raise http.Http404()
    try:
        clazz = models.StudentClass.objects.get(pk=clazz)
    except models.StudentClass.DoesNotExist:
        raise http.Http404()
    if student.stud_classes.filter(pk=clazz.pk).count() == 0:
        raise http.Http404()
    welfare = request.session.get(actions.SESSION_WELFARE, {})
    if student not in welfare:
        raise http.Http404()
    classes = welfare[student]
    if clazz in classes:
        del classes[clazz]
    else:
        classes[clazz] = committee.calc_scholarship_payment(clazz)
    welfare[student] = classes
    request.session[actions.SESSION_WELFARE] = welfare
    return http.HttpResponseRedirect("../")

@never_cache
def addelete_welfare_request(request, student, req):
    if not request.user.is_superuser and not request.user.has_perm(actions.DistributeWelfareAction.permission):
        raise http.Http404()
    try:
        student = models.Student.objects.get(pk=student)
    except models.Student.DoesNotExist:
        raise http.Http404()
    try:
        req = models.WelfareRequest.objects.get(pk=req)
    except models.WelfareRequest.DoesNotExist:
        raise http.Http404()
    if req.student != student:
        raise http.Http404()
    welfare = request.session.get(actions.SESSION_WELFARE, {})
    if student not in welfare:
        raise http.Http404()
    classes = welfare[student]
    if req in classes:
        del classes[req]
    else:
        classes[req] = req.cash
    welfare[student] = classes
    request.session[actions.SESSION_WELFARE] = welfare
    return http.HttpResponseRedirect("../../")

def give_scholarship(request):
    if not request.user.is_superuser and not request.user.has_perm(actions.DistributeScholarshipAction.permission):
        raise http.Http404()
    extra_context = csrf(request)
    return actions.DistributeScholarshipAction().done(request, extra_context)

def result_session(request):
    if not request.user.is_superuser and not request.user.has_perm(actions.SessionResultAction.permission):
        raise http.Http404()
    extra_context = csrf(request)
    return actions.SessionResultAction().process(request, extra_context=extra_context)

def scholarship_by_semester(request):
    if not request.user.is_superuser and not request.user.has_perm(actions.ScholarshipBySemesterAction.permission):
        raise http.Http404()
    extra_context = csrf(request)
    return actions.ScholarshipBySemesterAction().process(request, extra_context=extra_context)

def send_request(request):
    if not request.user.is_superuser and not request.user.has_perm(actions.SendWelfareRequestAction.permission):
        raise http.Http404()
    extra_context = csrf(request)
    return actions.SendWelfareRequestAction().process(request, extra_context=extra_context)

def students_by_group(request, group=None):
    if not request.user.is_superuser and not request.user.has_perm(actions.StudentsByGroupAction.permission):
        raise http.Http404()
    extra_context = csrf(request)
    return actions.StudentsByGroupAction().process(request, group, extra_context=extra_context)
